package top.blackr.folivora.common.security.auth.impl;

import net.dreamlu.mica.redis.cache.MicaRedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import top.blackr.folivora.common.core.exception.BizException;
import top.blackr.folivora.common.security.auth.LoginAuthentication;
import top.blackr.folivora.common.security.auth.SecUser;
import top.blackr.folivora.common.security.auth.authInfo.AuthenticationInfo;
import top.blackr.folivora.common.security.auth.authInfo.DefaultAuthenticationInfo;
import top.blackr.folivora.common.security.event.LoginAfterEvent;
import top.blackr.folivora.common.security.event.LoginBeforeEvent;

import java.util.Objects;

public class DefaultLoginService implements LoginService {

    @Autowired
    private MicaRedisCache redisCache;
    @Autowired
    private ApplicationEventPublisher publisher;

    @Override
    public SecUser authentication(LoginAuthentication authentication) {
        // 默认不实现，子类自行实现
        return null;
    }

    @Override
    public void loginBefore(LoginAuthentication authentication) {
        publisher.publishEvent(new LoginBeforeEvent(this, authentication));
    }

    @Override
    public SecUser loginAfter(LoginAuthentication authentication, SecUser user) {
        AuthenticationInfo authenticationInfo = new DefaultAuthenticationInfo(redisCache);

        if (Objects.isNull(user)) {
            throw new BizException("登陆认证失败，user 为null");
        }

        publisher.publishEvent(new LoginAfterEvent(this, authenticationInfo, authentication, user));
        return authenticationInfo.login(user);
    }
}
